package com.cloud.controller;

import com.cloud.domain.TOrder;
import com.cloud.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {
    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     *  getOrder1(Long id) 和 getOrder2(Long id)方法不能在一个类中实现，主要是因为利用RestTemplate发起远程调用时，
     *  注入的restTemplate实例若是使用了@LoadBalanced注解修饰，会使用Bibbon做拦截，会进行服务名称的替换，
     *     所以getOrder1不能用
     *  注入的restTemplate实例没有使用@LoadBalanced注解修饰，那么getOrder2中调用的服务CLOUD-PRODUCER无法解析到
     *  服务的IP和端口，无法获取到真实的地址
     * @param id
     * @return
     */

    @RequestMapping("/getOrder1")
    public TOrder getOrder1(Long id) {
        String urlStr = "http://localhost:8100/domain/t-order/getById?id=%d";
        String formatUrl = String.format(urlStr, id);
        ResponseEntity<TOrder> forEntity = restTemplate.getForEntity(formatUrl, TOrder.class);
        if (forEntity.getBody() != null) {
            TOrder body = forEntity.getBody();
            return body;
        }
        return null;
    }

    @RequestMapping("/getOrder2")
    public TOrder getOrder2(Long id) {
        String urlStr = "http://CLOUD-PRODUCER/domain/t-order/getById?id=%d";
        String formatUrl = String.format(urlStr, id);
        ResponseEntity<TOrder> forEntity = restTemplate.getForEntity(formatUrl, TOrder.class);
        if (forEntity.getBody() != null) {
            TOrder body = forEntity.getBody();
            return body;
        }
        return null;
    }

    /**
     * 使用Feign发起远程调用
     * @param id
     * @return
     */
    @RequestMapping("/getOrder")
    public TOrder getOrder(Long id) {
        if (id == null) {
            return null;
        }
        TOrder responseResult = iOrderService.getById(id);
        System.out.println(responseResult);
        return responseResult;
    }

}
